package controller

import (
	"github.com/gin-gonic/gin"
	"ylm.sl/common/convention/results"
	"ylm.sl/internal/api/request"
	"ylm.sl/internal/api/response"
	"ylm.sl/internal/service"
)

type GroupController struct {
	service service.IGroupService
}

func (c *GroupController) Save(context *gin.Context) {
	var req request.ShortLinkGroupSaveReqDTO
	err := context.ShouldBind(&req)
	if err != nil {
		results.Failure(context)
		return
	}
	if err = c.service.SaveGroup(context, req.Name); err != nil {
		results.Failure(context)
		return
	}
	results.Success(context)
}

func (c *GroupController) ListGroup(context *gin.Context) {
	var resp *[]response.ShortLinkGroupRespDTO

	resp, err := c.service.ListGroup(context)
	if err != nil {
		results.Failure(context)
		return
	}

	results.SuccessWithData(context, resp)
}

func (c *GroupController) UpdateGroup(context *gin.Context) {
	var req request.ShortLinkGroupUpdateReqDTO
	err := context.ShouldBind(&req)
	if err != nil {
		results.Failure(context)
		return
	}
	if err = c.service.UpdateGroup(context, req); err != nil {
		results.Failure(context)
		return
	}
	results.Success(context)
}

func (c *GroupController) DeleteGroup(context *gin.Context) {
	gid := context.PostForm("id")
	if err := c.service.DeleteGroup(context, gid); err != nil {
		results.Failure(context)
		return
	}
	results.Success(context)
}

func (c *GroupController) SortGroup(context *gin.Context) {
	var requestParam []request.ShortLinkGroupSortReqDTO
	err := context.ShouldBindJSON(&requestParam)
	if err != nil {
		results.Failure(context)
		return
	}
	err = c.service.SortGroup(context, &requestParam)
	if err != nil {
		results.Failure(context)
		return
	}
	results.Success(context)
}

func NewGroupController(service service.IGroupService) *GroupController {
	return &GroupController{service: service}
}
